<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="农场" prop="farmId">
        <el-input
          v-model="selectedFarmName"
          placeholder="请选择农场"
          clearable
          readonly
          @clear="handleClearFarm"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openFarmDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="违规时间" prop="violationTime">
        <el-date-picker
          style="width: 100%"
          v-model="formData.violationTime"
          type="date"
          value-format="x"
          placeholder="选择违规时间"
        />
      </el-form-item>
      <el-form-item label="违规原因" prop="violationReason">
        <el-input v-model="formData.violationReason" placeholder="请输入违规原因" />
      </el-form-item>
      <el-form-item label="违规详情" prop="violationDetail">
        <el-input v-model="formData.violationDetail" placeholder="请输入违规详情" />
      </el-form-item>
      <el-form-item label="证据文件" prop="evidenceFiles">
        <UploadFile
          v-model="formData.evidenceFiles"
          :file-type="['jpg', 'jpeg', 'png', 'pdf']"
          :file-size="10"
          :limit="5"
          directory="farm"
        />
        <div class="text-xs text-gray-400 mt-1">
          支持上传图片（jpg、png）或PDF文件，单个文件不超过10MB，最多上传5个文件
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

  <!-- 农场选择弹窗 -->
  <FarmSelectDialog ref="farmDialogRef" @confirm="handleFarmConfirm" />
</template>
<script setup lang="ts">
import { ViolationRecordApi, ViolationRecordVO } from '@/api/farm/violationrecord'
import { UploadFile } from '@/components/UploadFile'
import FarmSelectDialog from './FarmSelectDialog.vue'
import type { InfoVO } from '@/api/farm/info'

/** 农场违规记录 表单 */
defineOptions({ name: 'ViolationRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  farmId: undefined as number | undefined,
  violationTime: undefined,
  violationReason: undefined,
  violationDetail: undefined,
  evidenceFiles: '',
  remark: undefined
})
const formRules = reactive({
  farmId: [{ required: true, message: '农场不能为空', trigger: 'change' }],
  violationTime: [{ required: true, message: '违规时间不能为空', trigger: 'blur' }],
  violationReason: [{ required: true, message: '违规原因不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const farmDialogRef = ref() // 农场选择弹窗
const selectedFarmName = ref('') // 选中的农场名称

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ViolationRecordApi.getViolationRecord(id)
      // 确保证据文件字段是字符串类型（可能后端返回null或undefined）
      if (!formData.value.evidenceFiles) {
        formData.value.evidenceFiles = ''
      }
      // 如果有农场ID，需要加载农场信息以显示名称
      if (formData.value.farmId) {
        await loadFarmName(formData.value.farmId)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as ViolationRecordVO

    // 处理证据文件：如果是数组，转换为逗号分隔的字符串
    if (Array.isArray(data.evidenceFiles)) {
      data.evidenceFiles = data.evidenceFiles.join(',')
    }

    if (formType.value === 'create') {
      await ViolationRecordApi.createViolationRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await ViolationRecordApi.updateViolationRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    farmId: undefined as number | undefined,
    violationTime: undefined,
    violationReason: undefined,
    violationDetail: undefined,
    evidenceFiles: '',
    remark: undefined
  }
  selectedFarmName.value = '' // 清空农场名称
  formRef.value?.resetFields()
}

/** 加载农场名称 */
const loadFarmName = async (farmId: number) => {
  try {
    const { InfoApi } = await import('@/api/farm/info')
    const farm = await InfoApi.getInfo(farmId)
    selectedFarmName.value = farm.farmName
  } catch (error) {
    console.error('加载农场信息失败:', error)
  }
}

/** 打开农场选择弹窗 */
const openFarmDialog = () => {
  farmDialogRef.value?.open()
}

/** 农场选择确认 */
const handleFarmConfirm = (farm: InfoVO) => {
  formData.value.farmId = farm.id
  selectedFarmName.value = farm.farmName
}

/** 清空农场选择 */
const handleClearFarm = () => {
  formData.value.farmId = undefined
  selectedFarmName.value = ''
}
</script>
